<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <todo-header :list="list" @add="addFn" @isAll="changeAllFn"></todo-header>
    <todo-main :list="showArr" @del="delFn"></todo-main>
    <todo-footer :list="showArr" @changeCondition="changeFn"  @clearCompleted="clearFn"></todo-footer>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

import "./styles/base.css";
import "./styles/index.css";
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todoList")) || [],
      conStr: "all" // all(全部) completed(完成) incompleted(未完成)
    };
  },
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  methods: {
    delFn(id) {
      // 把id过滤掉
      this.list = this.list.filter((item) => item.id !== id);
    },
    addFn(name){
      this.list.push({
        id: Date.now(),
        name,
        isDone: false
      })
    },
    changeFn(str){ // 数据筛选-类型切换
      this.conStr = str;
    },
    clearFn(){ // 清空已完成
      this.list = this.list.filter(obj => !obj.isDone)
    },
    changeAllFn(bool){ // 全选改变事件
      this.list.forEach(obj => obj.isDone = bool);
    }
  },
  watch: { // 监测状态改变, 也要同步到本地
    list: {
      deep: true,
      handler(){
        localStorage.setItem("todoList", JSON.stringify(this.list));
      }
    }
  },
  computed: {
    showArr(){
      if (this.conStr == 'completed'){
        return this.list.filter(obj => obj.isDone)
      } else if (this.conStr == 'incompleted'){
        return this.list.filter(obj => !obj.isDone)
      } else {
        return this.list
      }
    }
  }
};
</script>

<style>
</style>